#include <windows.h>
#include <iostream>

using namespace std;

int tickets = 100;
CRITICAL_SECTION g_csA;
CRITICAL_SECTION g_csB;

DWORD WINAPI Fun1Proc(LPVOID lpParamter)
{
	while(TRUE)
	{
		EnterCriticalSection(&g_csA);
		Sleep(1);
		EnterCriticalSection(&g_csB);
		if(tickets > 0)
		{
			Sleep(1);
			cout<<"thread1 sell tickets : "<<tickets--<<endl;
			LeaveCriticalSection(&g_csB);
			LeaveCriticalSection(&g_csA);
		}
		else
		{
			LeaveCriticalSection(&g_csB);
			LeaveCriticalSection(&g_csA);
			break;
		}
	}
	return 0;
}

DWORD WINAPI Fun2Proc(LPVOID lpParamter)
{
	while(TRUE)
	{
		EnterCriticalSection(&g_csB);
		Sleep(1);
		EnterCriticalSection(&g_csA);
		if(tickets > 0)
		{
			Sleep(1);
			cout<<"thread2 sell tickets : "<<tickets--<<endl;
			LeaveCriticalSection(&g_csA);
			LeaveCriticalSection(&g_csB);
		}
		else
		{
			LeaveCriticalSection(&g_csA);
			LeaveCriticalSection(&g_csB);
			break;
		}
	}
	return 0;
}

int main()
{
	HANDLE hTread1;
	HANDLE hTread2;
	hTread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
	hTread2 = CreateThread(NULL, 0, Fun2Proc, NULL, 0, NULL);
	CloseHandle(hTread1);
	CloseHandle(hTread2);

	InitializeCriticalSection(&g_csA);
	InitializeCriticalSection(&g_csB);
	Sleep(5000);
	
	DeleteCriticalSection(&g_csA);
	DeleteCriticalSection(&g_csB);
	return 0;
}
